<template>
  <div class="page">
    <el-table
      :data="tableData"
      style="width: 100%"
      :default-sort="{ prop: 'id', order: 'ascending' }"
    >
      <!-- 修改：显示场馆名称而不是ID -->
      <el-table-column
        prop="venueName"
        label="场馆名称"
      ></el-table-column>
      
      <el-table-column
        prop="damageDetails"
        label="设备报修信息"
      ></el-table-column>
      
      <el-table-column
        prop="status"
        label="报修状态"
      >
        <template #default="scope">
          <el-tag
            :type="getTagType(scope.row.status)"
            effect="dark"
            round
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="修改报修信息" 
      width="45%" 
      destroy-on-close
      top="5vh"
      class="venue-dialog">
      <div class="dialog-header-divider"></div>
      <div class="form-container">
        <el-form 
          :model="venueForm" 
          :rules="rules" 
          ref="editFormRef" 
          label-width="110px" 
          class="venue-form"
          label-position="left">
          
          <!-- 修改：显示场馆名称而不是ID -->
          <el-form-item label="场馆名称" prop="venueId">
            <el-input 
              v-model="venueForm.venueName" 
              placeholder="场馆名称"
              prefix-icon="Position"
              disabled
            ></el-input>
          </el-form-item>
          
          <el-form-item label="设备报修信息" prop="damageDetails">
            <el-input 
              v-model="venueForm.damageDetails" 
              placeholder="请输入设备错误详细信息"
              prefix-icon="Position"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 6 }"
              maxlength="200"
              show-word-limit
            ></el-input>
          </el-form-item>
          
          <el-form-item label="报修状态" prop="status">
            <el-select 
              v-model="venueForm.status" 
              placeholder="请选择状态" 
              style="width: 100%"
              prefix-icon="Flag">
              <el-option 
                v-for="item in statusOptions" 
                :key="item" 
                :label="item" 
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false" :icon="Close">取消</el-button>
          <el-button type="primary" @click="updateVenue('editFormRef')" :icon="Check">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style>
  /* 样式保持不变 */
</style>

<script>
  import axios from 'axios'
  import request from '@/utils/request'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import { ref, onMounted } from 'vue'
  import { 
    Plus, Edit, Delete, 
    Position, Location, User, 
    Flag, Close, Check 
  } from '@element-plus/icons-vue'
  
  export default {
    setup() {
      const venueList = ref([])
      const venueMap = ref({}) // 新增：场馆ID到名称的映射
      const tableData = ref([])
      const editDialogVisible = ref(false)
      const venueForm = ref({
        id: '',
        venueId: '',
        venueName: '', // 新增：场馆名称字段
        damageDetails: '',
        status: ''
      })
      const statusOptions = ref(['维护中', '已维修', '未维修'])
      const rules = ref({
        venueId: [
          { required: true, message: '场馆ID不能为空', trigger: 'blur' }
        ],
        damageDetails: [
          { required: true, message: '请填写设备报修信息', trigger: 'blur' },
          { min: 3, message: '设备报修信息至少3个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择报修状态', trigger: 'change' }
        ]
      })
      const editFormRef = ref(null)
      
      // 获取场馆列表并创建映射
      const getVenueList = async () => {
        try {
          const response = await request.get('/getVenueInfo')
          venueList.value = response.data.data
          
          // 创建场馆ID到名称的映射
          venueMap.value = {}
          venueList.value.forEach(venue => {
            venueMap.value[venue.id] = venue.venueName
          })
        } catch (error) {
          console.error('获取场馆列表失败', error)
          ElMessage.error('获取场馆列表失败')
        }
      }
      
      // 获取报修信息并添加场馆名称
      const getVenueRepairInfo = () => {
        request.get('/getVenueRepairInfo').then(res => {
          if (res.data.code === 200) {
            // 添加场馆名称到每条报修记录
            tableData.value = res.data.data.map(item => {
              return {
                ...item,
                venueName: venueMap.value[item.venueId] || `未知场馆 (ID: ${item.venueId})`
              }
            })
          } else {
            ElMessage.error('获取场馆报修信息失败')
          }
        }).catch(err => {
          console.error('获取场馆报修信息失败:', err)
          ElMessage.error('获取场馆报修信息失败')
        })
      }

      const handleEdit = (row) => {
        venueForm.value = { 
          ...row,
          venueName: venueMap.value[row.venueId] || `未知场馆 (ID: ${row.venueId})`
        }
        editDialogVisible.value = true
        if (editFormRef.value) {
          editFormRef.value.resetFields()
        }
      }

      const updateVenue = (formRef) => {
        editFormRef.value.validate(valid => {
          if (!valid) {
            ElMessage.warning('请完善表单信息')
            return
          }
          const submitData = {
            id: venueForm.value.id,
            venueId: venueForm.value.venueId, // 提交时仍然使用venueId
            damageDetails: venueForm.value.damageDetails,
            status: venueForm.value.status
          }
          request.put(`/updateVenueRepair/${venueForm.value.id}`, submitData).then(res => {
            if (res.data.code === 200) {
              ElMessage.success('修改报修信息成功')
              editDialogVisible.value = false
              getVenueRepairInfo()
            } else {
              ElMessage.error('修改报修信息失败')
            }
          }).catch(err => {
            console.error('修改报修信息失败:', err)
            ElMessage.error('修改报修信息失败')
          })
        })
      }

      const handleDelete = (row) => {
        const venueName = venueMap.value[row.venueId] || `ID: ${row.venueId}`
        ElMessageBox.confirm(
          `确定要删除 "${venueName}" 的报修信息吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          request.delete(`/deleteVenueRepair/${row.id}`).then(res => {
            if (res.data.code === 200) {
              ElMessage.success('删除报修信息成功')
              getVenueRepairInfo()
            } else {
              ElMessage.error('删除报修信息失败')
            }
          }).catch(err => {
            console.error('删除报修信息失败:', err)
            ElMessage.error('删除报修信息失败')
          })
        }).catch(() => {
          ElMessage.info('已取消删除')
        })
      }
      
      // 根据报修状态返回对应的 tag 类型
      const getTagType = (status) => {
        if (status === '未维修') return 'warning'
        if (status === '维护中') return 'primary'
        if (status === '已维修') return 'success'
        return 'info'
      }

      // 初始化时获取场馆列表和报修信息
      onMounted(() => {
        getVenueList().then(() => {
          getVenueRepairInfo()
        })
      })
      
      return {
        tableData,
        editDialogVisible,
        venueForm,
        statusOptions,
        rules,
        editFormRef,
        Edit, Delete, 
        Close, Check,
        handleEdit,
        updateVenue,
        handleDelete,
        getTagType
      }
    }
  }
</script>